from pyamf.remoting.gateway.wsgi import WSGIGateway

from models import *

class CaseManager:
    def createCase(self,summary, openedBy, owner, status, origin, reason, priority, subject, contactID, accountID):
        case = Case(summary = summary, 
                    caseNumber = SequenceManager().generateNextSequenceNumber('case'),
                    openedBy = openedBy, 
                    owner = owner,
                    status = status,
                    origin = origin,
                    reason = reason,
                    priority = priority,
                    subject = subject, 
                    contact = Contact.all().filter('contactID = ', contactID).get(),
                    account = Account.all().filter('accountID = ', accountID).get() 
                    ) 
        case.put()
        return case

class SequenceManager:
    def generateNextSequenceNumber(self,name):
        sequence = Sequence.all().filter('name =', name).get()
        if sequence == None:
            sequence = Sequence(name=name,nextNumber=1)
            sequence.put()
            
        currNumber = sequence.nextNumber 
        sequence.nextNumber = sequence.nextNumber + 1
        sequence.put()
        return currNumber


def createCase(summary, openedBy, owner, status, origin, reason, priority, subject, contactID, accountID):
    return CaseManager.createCase(summary, openedBy, owner, status, origin, reason, priority, subject, contactID, accountID)

def echo(data):
	return data

class MyGateway(WSGIGateway):
	def __init__(self):
		myservices = {
            'myservice.echo': echo,
            'myservice.createCase': createCase,
		}
		WSGIGateway.__init__(self,myservices)
		
		
__all__ = ["MyGateway", "CaseManager"]